<template>
 <!-- 服务清单 -->
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top" v-if="isAdd">
                <div class="left">
                    <div>
                        <el-button size="small" type="primary" v-if="isBidding" plain class="btn-greenYellow" @click="selectPackage">选择包件</el-button>
                        <el-dropdown style="margin-right:10px" v-else trigger="click" @command="planClick">
                            <el-button type="primary" class="btn-greenYellow">
                                选择设备<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item
                                    v-for="item in planList"
                                    :key="item.value" :command="item.value"
                                >{{ item.label }}</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-button size="small" type="danger" class="btn-delete"  @click="deleteData">批量删除</el-button>
                    </div>
                </div>
            </div>
            <div>
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>
                 <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    @selection-change="changeSelect"
                    :row-class-name="tableRowClassName"
                    class="table"
                    :max-height="$store.state.tableHeight"
                    ref="tableRef"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                >
                    <el-table-column type="selection" width="50">
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        fixed
                        width="100px"
                        >
                        <template slot-scope="{ row }">
                            <div class="list_box">
                                <img src="@/assets/btn/delete.png" class="cancel_delete"
                                    @click="deleteEle(row)"
                                    title="删除"
                                />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="序号"
                            type="index"
                            width="100"
                            align="center"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="equipmentNumber"
                        label="设备编号"
                        min-width="200"
                        align="left"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="materialName"
                        label="设备名称"
                        min-width="200"
                        align="left"
                    >
                    </el-table-column>
                    <el-table-column prop="specificationModel" label="规格型号" width="100">
                         <template slot-scope="{ row }">
                            <el-input
                                @input="input(row)"
                                v-model="row.specificationModel"
                                clearable
                                v-if="!row.topClassId && isAdd"
                                maxlength="20"
                            ></el-input>
                            <div v-else>{{ row.specificationModel }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="计量单位" width="100">
                    </el-table-column>
                     <el-table-column prop="equipmentStatus" label="设备现状" width="150">
                        <template slot-scope="{ row }">
                            <el-select
                                @input="input(row)"
                                v-model="row.equipmentStatus"
                                clearable
                                v-if="!row.topClassId && isAdd"
                            >
                                <el-option
                                    v-for="(item,index) in equipmentStatusList"
                                    :key="index"
                                    :label="item"
                                    :value="item"
                                ></el-option>
                            </el-select>
                            <div v-else>{{ row.equipmentStatus }}</div>
                        </template>
                    </el-table-column>
                     <el-table-column prop="content" label="维修/安装内容" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <el-input
                                @input="input(row)"
                                v-model="row.content"
                                clearable
                                v-if="!row.topClassId && isAdd"
                                maxlength="500"
                            ></el-input>
                            <div v-else>{{ row.content }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量"  align="right"  width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.quantity"
                                placeholder="请输入内容"
                                v-if="isEdit"
                                v-enterJustFloat2
                               @change="onCalcAmount(row,'quantityUpdateFlag')"
                            ></el-input>
                            <div v-else>{{ row.quantity }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.numberRecords)"
                                @clickIcon="clickIcon(row.numberRecords)"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价(元)" align="right" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPrice"
                                placeholder="请输入内容"
                                v-if="isEdit"
                                v-enterJustFloat
                                @change="onCalcAmount(row,'unitPriceUpdateFlag')"
                            ></el-input>
                            <div v-else>{{ row.unitPrice }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.priceRecords)"
                                @clickIcon="clickIcon(row.priceRecords)"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" align="right" width="120">
                        <template slot-scope="{ row }">
                            <div>{{ row.amount }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.amountRecords)"
                                @clickIcon="clickIcon(row.amountRecords)"
                            />
                        </template>
                    </el-table-column>
              </el-table>
            </div>
         </div>
    </div>
</template>
<script>
import { isFourInput, isNumInput, isTwoInput, isFourInputJust } from '@/utils/rules.js'
import { mapState, mapMutations } from 'vuex'
import { selectDataClient } from '@/utils/common'
import historyUpdateTable from '@/pages/balanceContract/materialContract/ctMaterialPurchase/components/historyUpdateTable.vue'
import fn from '@/utils/checkEmpty.js'
import {  getUuid } from '@/utils/common'
export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        },
        billid: {
            type: String,
            default: ''
        },
        contractListTable: {
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: {
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: {
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        //是否可以新增
        isAdd: {
            default: true
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
        subcontract: { //接口
        },
        dtlList: { //包件清单
            type: Array,
            default: function () {
                return []
            }
        },
        state: { //流程状态
            type: Number
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        },
        ...mapState({
            serverList: state => state.contract.ctClassify.serverList, //服务清单数据
            supplyType: state => state.contract.ctClassify.supplyTypeList
        }),
        //判断数据是否为空
        checkEmpty () {
            return datas=>{
                return !fn.checkEmpty(datas)
            }
        },
    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: false,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
        dtlList: {
            handler (newName) {
                this.$emit('isMonitorTaxRate')
                newName.forEach(item=>{
                    if(!this.tableData.find(x=>(x.oriBillId === item.equipmentId) && x.changeType !== -1)) {
                        const obj =  {
                            uuid: getUuid(),
                            billId: '',
                            billNo: '',
                            amount: 0, //预算金额(元)
                            unitPrice: 0, //预算单价(元)
                            changeType: 1,
                            quantity: item.num, //数量
                            dtlId: '', //物资总计划明细id
                            customId: getUuid(),
                            typeId: item.materialTypeId, //物资类别id(
                            typeName: item.type, //物资类别名称
                            materialId: item.materialNameId, //物资id
                            materialName: item.name, //物资名称
                            planQuantity: 0, //计划数量
                            specificationModel: item.specs, //规格型号
                            textureOfMaterial: item.texture, //材质
                            unit: item.unit, //计量单位
                            sourceId: this.billid, //源单id
                            oriUnitPrice: '', //原单价
                            oriQuantity: item.num, //原单价
                            oriBillId: item.recordId, //原id
                            equipmentNumber: item.equipmentNumber, //设备编号
                            'amountAfterChange': 0,
                            'amountUpdateFlag': true,
                            'changeState': 0,
                            'content': '',
                            'destination': '',
                            'equipmentStatus': '',
                            'listType': 4,
                            'mileage': '',
                            'mileageAfterChange': '',
                            'oneLevelTypeId': '',
                            'oneLevelTypeName': '',
                            'placeOfDeparture': '',
                            'quantityAfterChange': 0,
                            'quantityUpdateFlag': true,
                            'unitPriceAfterChange': 0,
                            'unitPriceUpdateFlag': true
                        }
                        this.tableData.push(obj)
                    }
                })

            },
            immediate: false,
            deep: true
        }
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            addFlag: true,
            materialListTeam: [], //存储执行队列
            materialListIndex: 0,
            showTable: true,
            tableSelect: [],
            equipmentStatusList: ['良好', '一般', '差'], //设备现状
            planList: [
                { value: 1, label: '维保申请' },
                { value: 2, label: '大修计划' },
                { value: 3, label: '设备台账' },
            ], //1 :'维保申请', 2:'大修计划', 3:'设备台账'
        }
    },
    created () {
    },
    mounted () {
        this.setServerList([])
    },
    methods: {
        ...mapMutations(
            'contract', ['setServerList']
        ),
        ...mapMutations(['setHistoryTableData', 'setSelectedInfo']),
        // 获取列表数据
        getData () {
            this.showTable = false
            //获取设备清单
            this.subcontract.getList({
                sourceId: this.billid,
            }).then(res => {
                res = res.code ? [] : res
                res.forEach(item=>{
                    item.typeId = parseInt(item.typeId)
                    item.changeType = 0
                    if(this.state === 1) {
                        item.quantityUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                this.tableData = res
                this.showTable = true
            })
        },
        // 输入后计划金额
        onCalcAmount (row, feild) {
            this.$emit('isMonitorTaxRate')
            if(this.state === 1) {
                row.amountUpdateFlag = true
                row[feild] = true
            }
            row.amount = row.changeType !== -1 ?  ( parseFloat(row.quantity ? row.quantity : 0) * parseFloat(row.unitPrice ? row.unitPrice : 0) ).toFixed(2)  : 0
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }

        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                return `class-${row.billId} row-hide`
            }else{
                return `class-${row.billId} row-show`
            }

        },
        isFourInput (event) {
            isFourInput(event)
        },
        isFourInputJust (event) {
            isFourInputJust(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        isTwoInput (event) {
            isTwoInput(event)
        },
        //单价类型切换
        unitPriceTypeChange (row) {
            const fn = data=>{
                data.forEach(item=>{
                    item.unitPriceType = row.unitPriceType
                    if(!item.isDetailed) {
                        fn(item.children)
                    }
                    this.mapTableData[row.billid] = row
                })
            }
            if(!row.isDetailed) {
                fn(row)
            }else{
                this.mapTableData[row.billid] = row
            }
        },
        //单价切换
        unitPriceChange (row) {
            row.children.forEach(item=>{
                item.unitPrice = row.unitPrice
                this.mapTableData[item.billid] = item
                this.onCalcAmount(item)
            })
            this.mapTableData[row.billid] = row
        },
        //数量切换
        quantityChange (row) {
            const parent = this.mapTableData[row.parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round(item.changeType !== -1 ? item.quantity : 0)
            }, 0)
            // 赋值汇总数据给父级
            parent.quantity = countSibling // 赋值汇总数据给父级
        },
        clickIcon (list) {
            this.setHistoryTableData(list)
        },
        deleteData () {
            if(this.tableSelect.length === 0) return
            this.clientPop('err', this.moreDeleteListErr(this.tableSelect), () => {
                this.$emit('isMonitorTaxRate')
                this.tableSelect.forEach(item=>{
                    if(item.changeType === 1 ) {
                        let index = this.tableData.findIndex(x=>x === item)
                        this.tableData.splice(index, 1)
                    }else{
                        item.changeType = -1
                    }
                })
            })
        },
        deleteEle (row) {
            this.clientPop('err', this.oneDeleteListErr, () => {
                this.$emit('isMonitorTaxRate')
                if(row.changeType === 1 ) {
                    let index = this.tableData.findIndex(x=>x === row)
                    this.tableData.splice(index, 1)
                }else{
                    row.changeType = -1
                }
            })
        },
        changeSelect (selection) {
            this.tableSelect = selection
        },
        changeTypeId (row) {
            if( !row.typeId )return
            row.typeName = this.serverType.find(x => x.value === row.typeId).label
            this.input(row)
        },
        //改变changeType
        input (row) {
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }
        },
        //选择包件
        selectPackage () {
            const tableData = [...this.tableData]
            let ids = tableData.filter(x=>(x.oriBillId && x.changeType !== -1)).map(x=>x.oriBillId)
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/tender/materialServiceProcurement/dtl/dtlListPage', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'type': 3, //清单类型写死1
                    'packageId': this.mainInfo.secondParty.dtlId
                }),
                Title: '选择包件清单' // 标题
            }).then(val => {
                val.forEach(item=>{
                    if(!this.tableData.find(x=>(x.oriBillId === item.recordId) && x.changeType !== -1)) {
                        const obj =  {
                            uuid: getUuid(),
                            billId: '',
                            billNo: '',
                            amount: 0, //预算金额(元)
                            unitPrice: 0, //预算单价(元)
                            changeType: 1,
                            quantity: item.num, //数量
                            dtlId: '', //物资总计划明细id
                            customId: getUuid(),
                            typeId: item.materialTypeId, //物资类别id(
                            typeName: item.type, //物资类别名称
                            materialId: item.materialNameId, //物资id
                            materialName: item.name, //物资名称
                            planQuantity: 0, //计划数量
                            specificationModel: item.specs, //规格型号
                            textureOfMaterial: item.texture, //材质
                            unit: item.unit, //计量单位
                            sourceId: this.billid, //源单id
                            oriUnitPrice: '', //原单价
                            oriQuantity: item.num, //原单价
                            oriBillId: item.recordId, //原id
                            equipmentNumber: item.equipmentNumber, //设备编号
                            'amountAfterChange': 0,
                            'amountUpdateFlag': true,
                            'changeState': 0,
                            'content': '',
                            'destination': '',
                            'equipmentStatus': '',
                            'listType': 4,
                            'mileage': '',
                            'mileageAfterChange': '',
                            'oneLevelTypeId': '',
                            'oneLevelTypeName': '',
                            'placeOfDeparture': '',
                            'quantityAfterChange': 0,
                            'quantityUpdateFlag': true,
                            'unitPriceAfterChange': 0,
                            'unitPriceUpdateFlag': true
                        }
                        this.tableData.push(obj)
                    }
                })
            })

        },
        //选择设备
        selectPlan (val, listType) {
            val.forEach(item=>{
                if(!this.tableData.find(x=>(x.oriBillId === item.equipmentNo) && x.changeType !== -1)) {
                    const obj =  {
                        'amount': 0,
                        'amountAfterChange': 0,
                        'amountUpdateFlag': true,
                        'billId': '',
                        'changeState': 0,
                        'changeType': 1,
                        'content': '',
                        'destination': '',
                        'equipmentNumber': item.equipmentNo,
                        'equipmentStatus': '',
                        'listType': listType,
                        'materialName': item.equipmentName,
                        'mileage': '',
                        'mileageAfterChange': '',
                        'oneLevelTypeId': '',
                        'oneLevelTypeName': '',
                        'oriBillId': item.equipmentNo,
                        'oriQuantity': 0,
                        'oriUnitPrice': 0,
                        'placeOfDeparture': '',
                        'quantity': 0,
                        'quantityAfterChange': 0,
                        'quantityUpdateFlag': true,
                        'specificationModel': item.specificationModel,
                        'textureOfMaterial': '',
                        'typeId': '',
                        'typeName': '',
                        'unit': item.unit,
                        'unitPrice': 0,
                        'unitPriceAfterChange': 0,
                        'unitPriceUpdateFlag': true,
                        sourceId: this.billid, //源单id
                    }
                    this.tableData.push(obj)
                }
            })
        },
        //选择计划点击事件
        planClick (index) {
            this.$emit('isMonitorTaxRate')
            if(index === 1 || index === 2) {
                const listType = index === 1 ? 5 : 6  //5。大修计划,6.维保申请
                const ids = this.tableData.filter(x=>x.listType === listType && x.changeType !== -1).map(x=>x.oriBillId)
                // 弹窗选择数据
                selectDataClient({
                    SelectServiceToken: '/common/MaintenanceRepairSelect', // 客户端对应方法名
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                    InitParamsStr: index,
                    Title: '选择设备' // 标题
                }).then(val => {
                    this.selectPlan(val, listType)
                })
            }else{
                const listType  = 7
                // const ids = this.tableData.filter(x=>x.listType === listType && x.changeType !== -1).map(x=>x.oriBillId)
                // 弹窗选择数据
                selectDataClient({
                    SelectServiceToken: '/facilityaccount/account/all/equipment', // 客户端对应方法名
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                    InitParamsStr: JSON.stringify({
                        'states': []
                    }),
                    Title: '选择设备' // 标题
                }).then(val => {

                    this.selectPlan(val, listType)
                })
            }
        },
        //清除数据
        clearData () {
            for(let i = 0;i < this.tableData.length;i++) {
                if( this.tableData[i].changeType === 1 ) {
                    this.tableData.splice(i, 1)
                    i--
                }else{
                    this.tableData[i].changeType = -1
                }
            }
        },
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep.el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(2){
            .cell{
                justify-content: center;
            }
        }
        td:nth-child(6),td:nth-child(7),td:nth-child(8){
            .cell{
                justify-content: flex-end;
            }
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
</style>
